use std::fs;
use std::io::{BufWriter, Read, Write, BufReader,BufRead};
use std::fs::File;

pub fn _read_file(path: &str) -> Result<String, std::io::Error> {
    let mut file = File::open(path)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    Ok(contents)
}
// pub fn write_file(path: &str, contents: &str) -> Result<(), std::io::Error> {
//     let mut file = File::create(path)?;
//     file.write_all(contents.as_bytes())?;
//     Ok(())
// }


pub fn read_lines_from_file(path: &str) -> Result<Vec<String>,anyhow::Error> {
    let file = File::open(path)?;
    let reader = BufReader::new(file);

    // 读取文件的所有行
    let mut lines = Vec::new();
    for line in reader.lines() {
        lines.push(line?);
    }

    Ok(lines)
}
pub fn _del_file(path: &str){
    fs::remove_file(path).unwrap()
}
pub fn append_string_to_file(path: &str, data: &str) -> Result<(), Box<dyn std::error::Error>> {
    let file = fs::OpenOptions::new().create(true).append(true).open(&path)?;
    let mut file = BufWriter::new(file);
    // let res = file.write_all(&data.as_bytes());
    // println!(">>>>>>>>>>>>>>>>>>>>>>>>>>.res {:?}",res);
    // 将文本写入文件
    match file.write_all(data.as_bytes()) {
        Err(e) => {
            // 处理写入错误
            eprintln!("===Error writing to file: {}", e);
        },
        Ok(_) => {
            // 写入成功
            println!(">>>Successfully wrote to file: {}", path);
        },
    }
    // let _remaining = file.write(&data.as_bytes())?;
    // if remaining != 0 {
    // }
    // // 绝对明确的刷新buffwriter
    // file.flush()?;
    Ok(())
}
pub fn _append_data_to_file(path: &str, data: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
    let file = fs::OpenOptions::new().create(true).append(true).open(&path)?;
    let mut file = BufWriter::new(file);
    file.write_all(&data)?;
    let remaining = file.write(&data)?;
    if remaining != 0 {
    }
    file.flush()?;
    Ok(())
}

// pub fn read_by_line(path: &str)  -> Result<Vec<String>, ErrorKind> {
//     read_lines(path)
// }

// pub fn read_by_line_num(nums:Vec<u32>) {
//     if let Ok(lines) = read_lines("src/main.rs") {
//         let mut l:u32 = 0;
//         lines.for_each(|line| {
//             if let Ok(line) = line {
//                 if nums.contains(&l) {
//                     println!("{}", line);
//                 }
//             }
//             l += 1;
//         });
//     }
// }

// fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
// where
//     P: AsRef<Path>,
// {
//     let file = File::open(filename)?;
//     Ok(io::BufReader::new(file).lines())
// }